import { ref, reactive, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import chatApi from '../api/chat';

const createMessage = (sender, content, type = 'text') => ({
    id: Date.now() + Math.random(),
    sender,
    content,
    type,
    timestamp: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
});

export function useChat() {
    // State
    const messages = ref([]);
    const inputMessage = ref('');
    const isTyping = ref(false);
    const messagesContainer = ref(null);

    // Mock conversation history data
    const conversationHistory = ref([
        { id: 1, title: '关于用户增长的分析', lastTime: '昨天' },
        { id: 2, title: '上周工作报告生成', lastTime: '3天前' },
        { id: 3, title: 'Vue.js性能优化技巧', lastTime: '上周' },
    ]);
    const currentConversation = ref(null);


    // Method to scroll to the bottom of the messages container
    const scrollToBottom = () => {
        nextTick(() => {
            if (messagesContainer.value) {
                messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
            }
        });
    };

    // Method to send a message
    const sendMessage = async (messageText = inputMessage.value) => {
        const text = messageText.trim();
        if (!text || isTyping.value) return;

        // Add user message to list
        messages.value.push(createMessage('user', text));
        inputMessage.value = '';
        scrollToBottom();
        
        // Start AI response
        isTyping.value = true;
        const assistantMessage = createMessage('assistant', '');
        messages.value.push(assistantMessage);
        scrollToBottom();

        const history = messages.value.slice(0, -2); // Exclude the current exchange

        // Handle streaming response from API
        chatApi.getChatResponse(text, history, {
            onChunk: (chunk) => {
                if (!chunk.done) {
                    assistantMessage.content += chunk.content;
                    scrollToBottom();
                }
            },
            onEnd: () => {
                isTyping.value = false;
                // Potentially add suggestions or other actions here
            }
        });
    };

    // Method to load a conversation (mock implementation)
    const loadConversation = (conversation) => {
        currentConversation.value = conversation;
        ElMessage.info(`正在加载对话: "${conversation.title}"`);
        messages.value = [
            createMessage('user', '你好，我们来继续上次的讨论。'),
            createMessage('assistant', `好的，我们上次聊到关于**${conversation.title}**的话题，您希望从哪里开始呢？`)
        ];
        scrollToBottom();
    };
    
    // Method to start a new conversation
    const newConversation = () => {
        currentConversation.value = null;
        messages.value = [];
        ElMessage.success('新的对话已开始');
    };

    return {
        messages,
        inputMessage,
        isTyping,
        messagesContainer,
        conversationHistory,
        currentConversation,
        sendMessage,
        loadConversation,
        newConversation,
        scrollToBottom,
    };
} 